package com.atguigu.flink.chapter07.state;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.streaming.util.serialization.SimpleStringSchema;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class Flink10_State_Kafka_Flink_Kafka {
    public static void main(String[] args) throws Exception {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        Configuration conf  = new Configuration();
        conf.setInteger("rest.port", 20000);

        StreamExecutionEnvironment env = StreamExecutionEnvironment
                .getExecutionEnvironment(conf)
                .setParallelism(3);

        env.enableCheckpointing(2000);
        env.setStateBackend(new FsStateBackend("hdfs://hadoop162:8020/ck"));

        // 设置checkpoint的语义：严格一次
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);

        // 确认 checkpoints 之间的时间会进行 500 ms
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);

        // Checkpoint 必须在一分钟内完成，否则就会被抛弃
        env.getCheckpointConfig().setCheckpointTimeout(60000);

        // 同一时间只允许一个 checkpoint 进行
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);

        // 开启在 job 中止后仍然保留的 externalized checkpoints
        env.getCheckpointConfig()
                .enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);


        Properties sourceProps = new Properties();
        sourceProps.setProperty("bootstrap.servers", "hadoop162:9092,hadoop163:9092");
        sourceProps.setProperty("group.id", "Flink10_State_Kafka_Flink_Kafka1112");
        sourceProps.setProperty("auto.offset.reset", "latest"); // 如果没有消费记录， 则从最新的消费
        sourceProps.setProperty("isolation.level", "read_committed"); // 只消费事务二阶段提交之后的数据

        Properties sinkProps = new Properties();
        sinkProps.setProperty("bootstrap.servers", "hadoop162:9092,hadoop163:9092");
        sinkProps.setProperty("transaction.timeout.ms", 15 * 60 * 1000 + "");

        SingleOutputStreamOperator<Tuple2<String, Long>> stream = env
                .addSource(new FlinkKafkaConsumer<String>("s1", new SimpleStringSchema(), sourceProps))
                .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                        for (String word : value.split(" ")) {
                            out.collect(Tuple2.of(word, 1L));
                        }
                    }
                })
                .keyBy(t -> t.f0)
                .sum(1);

        stream
                .addSink(new FlinkKafkaProducer<Tuple2<String, Long>>(
                        "default",
                        new KafkaSerializationSchema<Tuple2<String, Long>>() {
                            @Override
                            public ProducerRecord<byte[], byte[]> serialize(Tuple2<String, Long> element, @Nullable Long timestamp) {
                                return new ProducerRecord<>("s2", (element.f0 + "_" + element.f1).getBytes(StandardCharsets.UTF_8));
                            }
                        },
                        sinkProps,
                        FlinkKafkaProducer.Semantic.EXACTLY_ONCE // 利用kafka的事务， 实现严格一次
                ));
        /*stream.addSink(new SinkFunction<Tuple2<String, Long>>() {
            @Override
            public void invoke(Tuple2<String, Long> value, Context context) throws Exception {
                if (value.f0.equals("a")) {
                    throw new RuntimeException("xxxxxx");
                }
            }
        });*/
        env.execute();

    }
}
